package com.qf.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.common.AliyunOSSConstants;
import com.qf.entity.User;
import com.qf.entity.UserDTO;
import com.qf.service.UserService;
import com.qf.util.*;
import io.jsonwebtoken.Claims;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;


@RestController
@RequestMapping("/user")

public class UserController {

    private Logger logger = LogManager.getLogger(UserController.class);

    private HashMap<String,Object> map = new HashMap<>();
    @Autowired
    private UserService Service;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private RedisUtil redisUtil;

    /*
    * 根据用户名和密码登录
    * */
    @PostMapping("/login")
    public R login(@RequestBody User user){
        System.out.println(user);
        User loginUser =  Service.login(user);
        if(loginUser!=null){
            /** 拼接用户头像地址 */
            // 判断一下是否是默认头像
            String defaultAvatar = "https://q1.itc.cn/q_70/images03/20241107/8355cb2b79cf4a319b611ebfafe8df1c.jpeg";
            if(!loginUser.getAvatar().equals(defaultAvatar)){
            loginUser.setAvatar(AliyunOSSConstants.PUBLIC_URL + loginUser.getAvatar());
            }

            //登录成功，返回token
            String token = UUID.randomUUID().toString();
            //用map代替
            map.put(token,user);
            map.put("token",token);
            return R.ok(map);
        }else {
            //否者登录失败
            return R.fail();
        }
    }

    /*
    * 根据token获得用户信息
    * */
    @GetMapping("/info")
    public R info(String token){
        System.out.println(token);
        //根据token获得信息
        User user = (User) map.get(token);
        System.out.println(user);
        if(user!=null){
            return R.ok(user);
        }else {
            return R.fail();
        }
    }


    /*
    * 退出登录
    * */
    @PostMapping("/logout")
    public R logout(String token){
        //根据token从redis中删除用户信息
        map.remove(token);
        return R.ok();
    }

    /*
    * 查询全部
    * */
    @GetMapping("/find/all")
    public R findAll(){
        List<User> list= Service.findAll();
        return R.ok(list);
    }

    /*
     * 更新
     * */
    @PostMapping("/update")
    public R update(@RequestBody User user){
        boolean ok = Service.update(user);
        return R.ok(ok);
    }

    /*
    * 分页查询全部
    * */
    @GetMapping("/page")
    public R findAll2(UserDTO userDTO){
        // 1. 开始分页 或 开启分页
        PageHelper.startPage(userDTO.getPageNum(),userDTO.getPageSize());
        // 2. 查询所有的用户
        List<User> list = Service.findAll2(userDTO);
        // 3. 将查询出的用户集合交给pageInfo进行分页
        PageInfo<User> pageInfo = new PageInfo<>(list);
        // 4. 将分页的数据返回给前端
        return R.ok(pageInfo);
    }

    /*
    *删除一个
     **/
    @GetMapping("/delete")
    public R delete(int id){
        boolean ok = Service.deleteById(id);
        return R.ok(ok);
    }

    /*
    * 批量删除
    * */
    @GetMapping("/user/delete/batch")
    public R batchDelete(@RequestParam List<Integer> ids){
        System.out.println("batchDelete = " + ids);
        boolean ok = Service.batchDelete(ids);
        return R.ok(ok);
    }

    /*
    * 添加
    * */
    @PostMapping("/add")
    public R add(@RequestBody User user){
        boolean ok = Service.add(user);
        return R.ok(ok);
    }

    @PostMapping("/login2")
    public R login2(@RequestBody User user) throws Exception {
        // 根据用户名+密码查数据库,将信息存储到redis,查到返回token
        logger.debug("解密前密码: " + user.getPassword( ));
        String pwd = RsaUtils.decryptByPrivateKey(user.getPassword( ));
        logger.debug("解密后密码: " + pwd);

        // 对密码再次使用bcrypt加密
        user.setPassword(pwd);


        String token = Service.login2(user);
        return R.ok(token);
    }

    @GetMapping("/getInfo2")
    public R getInfo2(String token) {
        // 根据token从redis中获取用户信息
        // Claims claims = jwtUtils.parseJWT(token);
        // Object uuid = claims.get("uuid");
        // User sysUser = (User) redisUtil.getCacheObject("user:key:"+uuid);
        // System.out.println("sysUser = " + sysUser);
        // return R.ok(sysUser);
        Authentication authentication = SecurityContextHolder.getContext( ).getAuthentication( );
        String username = authentication.getName( );
        // 通过用户名查询用户详情
        User user = Service.getUserByUsername(username);
        // 判断用户的头像是否是默认头像,如果不是,则加上OSS的公共前缀
        String defalut_avatar = "https://q1.itc.cn/q_70/images03/20241107/8355cb2b79cf4a319b611ebfafe8df1c.jpeg";
        if (!user.getAvatar().equals(defalut_avatar)) {
            user.setAvatar(AliyunOSSConstants.PUBLIC_URL + user.getAvatar());
        }
        return R.ok(user);
    }


    /**
     * 系统用户退出
     */
    @GetMapping("/logout2")
    public R logout2(String token) {
        Claims claims = jwtUtils.parseJWT(token);
        Object uuid = claims.get("uuid");
        redisUtil.deleteObject("user:key:"+uuid);
        return R.ok( );
    }


    /**
     * 注册用户
     */
    @PostMapping("/register")
    public R registerUser(@RequestBody User user) throws Exception {
        // 正常来说,应该前端使用JSEncrypt加密密码,这里需要解密后,再对对面加密注册.这里暂时不做处理,直接加密
        // 对前端传递的密码进行解密
        String pwd = RsaUtils.decryptByPrivateKey(user.getPassword( ));;
        // 对密码进行bcrypt加密
        pwd = PwdEncrypt.hashPasswordByBCrypt(pwd);
        user.setPassword(pwd);
        // 注册用户--此时存储到数据库中的密码是加密后的密码
        Service.add(user);
        return R.ok( );
    }

}
